<template>
  <div class="page-list-live">
    <PageList>
      <template #header>在线率统计</template>
      <template #filter>
        <ListFilter :form="topFilter" :select-value="true" @search="serchHandler" @reset="handleReset" @changItemHandler="changItemHandler">
          <el-button slot="searchButtons" type="info" icon="el-icon-download" @click="handleExport">导出</el-button>
        </ListFilter>
      </template>
      <template #table>
        <ListTable ref="RefListTable" :loading="tableLoading" :table-data="tableData" :table-col="tableCol" />
      </template>
    </PageList>
  </div>
</template>

<script>
import listMixin from '@/mixins/list'
import ListFilter from '@/components/ListFilter'
import { tenantOnline } from '@/api/api'
import { getToken } from '@/utils/auth'
export default {
  components: { ListFilter },
  mixins: [listMixin],
  data() {
    return {
      startDate: (function () {
        // 现在的时间
        var da = new Date()
        // 获取当前月份
        var currentMonth = da.getMonth() + 1
        return da.getFullYear() + '-' + currentMonth + '-' + '01' + ' ' + '00:00:00'
        // return da.getFullYear() + '-' + currentMonth + '-' + '01'
      })(),
      endDate: (function () {
        // 现在的时间
        var date = new Date()
        // 获取当前月份
        var currentMonth = date.getMonth()
        // 获取下一个月
        var nextMonth = ++currentMonth
        // 获取下个月的1号
        var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1)
        // 设置一天的时间
        var oneDay = 1000 * 60 * 60 * 24
        // 上个月的第一天减去一天得到当前月的最后一天的时间
        var lastTime = new Date(nextMonthFirstDay - oneDay)
        // 得到当前月
        var month = parseInt(lastTime.getMonth() + 1)
        // 得到当前月最后一天
        var day = date.getDate()
        if (month < 10) {
          month = '0' + month
        }
        if (day < 10) {
          day = '0' + day
        }
        return date.getFullYear() + '-' + month + '-' + day + ' ' + '23:59:59'
        // return date.getFullYear() + '-' + month + '-' + day
      })(),
      startTime: null,
      endTime: null,
      topFilter: {
        enterTime: {
          label: '时间选择',
          type: 'date',
          arr: ['startTime', 'endTime']
        }
      },
      tableData: [],
      tableCol: [
        { prop: 'tenantName', label: '工点' },
        { prop: 'shouldOnlineHours', label: '应当在线时间(小时)' }, //
        { prop: 'actualOnlineHours', label: '实际在线时间(小时)' },
        {
          prop: 'onlinePercent',
          label: '在线率',
          formatter(row, col, cell) {
            const str = cell.toString()
            const ind = str.indexOf('.')
            const newStr = str.substr(0, ind + 3)
            return newStr
          }
        }
      ]
    }
  },
  async mounted() {
    this.startTime = this.startDate
    this.endTime = this.endDate
    await this.$store.dispatch('user/setAttendanceDate', {
      EnterTimeStart: this.startTime,
      EnterTimeEnd: this.endTime,
      status: true
    })
  },
  async beforeDestroy() {
    await this.$store.dispatch('user/setAttendanceDate', { EnterTimeStart: null, EnterTimeEnd: null, status: false })
  },
  methods: {
    changItemHandler(obj) {
      if (obj.key === 'enterTime') {
        this.startTime = obj.val[0]
        this.endTime = obj.val[1]
      }
    },
    handleExport() {
      var that = this
      const url = process.env.VUE_APP_BASE_API + 'TenantOnline/AllOnlineDownload'
      const xhr = new XMLHttpRequest()
      xhr.open('POST', url, true)
      // xhr.setRequestHeader('content-type', 'application/octet-stream')
      xhr.setRequestHeader('content-type', 'application/json')
      xhr.setRequestHeader('Authorization', 'Bearer ' + getToken())
      xhr.responseType = 'blob' // 返回类型blob  blob 存储着大量的二进制数据
      xhr.onload = function (result) {
        console.info('result', result)
        if (xhr.status === 200) {
          const blob = this.response
          const reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = function (e) {
            var a = document.createElement('a') // 转换完成，创建一个a标签用于下载
            a.download = that.startTime + '~' + that.endTime + '在线率统计.xlsx'
            a.href = e.target.result
            document.body.appendChild(a) // 修复firefox中无法触发click
            a.click()
            document.body.removeChild(a)
          }
        } else {
          this.$message.error('导出失败！')
        }
      }
      xhr.send(JSON.stringify({ pageIndex: 1, pageSize: 100, endTime: this.endTime, startTime: this.startTime })) // 发送ajax请求
    },
    // 搜索
    serchHandler(obj) {
      const arr = obj.search.map((item) => {
        return { key: item.key, value: item.value }
      })

      arr.forEach((item) => {
        obj[item.key] = item.value
      })
      delete obj.search
      this.getList(obj)
    },
    async handleReset(obj) {
      await this.$store.dispatch('user/setAttendanceDate', {
        EnterTimeStart: this.startDate,
        EnterTimeEnd: this.endDate,
        status: true
      })

      this.startTime = this.startDate
      this.endTime = this.endDate
      this.getList({ pageIndex: 1, pageSize: 10, endTime: this.enterTime, startTime: this.startTime })
    },
    async getList(query) {
      this.tableLoading = true
      try {
        if (this.endTime) {
          query.endTime = this.endTime
          query.startTime = this.startTime
        } else {
          query.endTime = query.EnterTimeEnd
          query.startTime = query.EnterTimeStart
        }
        const {
          data: { items, pageIndex, count }
        } = await tenantOnline('POST', query, true)
        this.tableData = []
        this.tableData = items
        this.$nextTick(() => {
          this.$refs['RefListTable'].update({ page: pageIndex, count })
          this.tableLoading = false
        })
      } catch (err) {
        if (err.response.status === 404) {
          this.$message.warning('无数据！')
          this.tableData = []
        }
      }
      this.tableLoading = false
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
